/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package ant.antsys;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.DOMElementWriter;
import org.apache.tools.ant.util.DateUtils;
import org.apache.tools.ant.util.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
 * 
 * generate XML report from test result
 * @see TestSuiteResult
 */

class XMLReport implements XMLConstants{

    private static final double ONE_SECOND = 1000.0;

    /** constant for unnnamed testsuites/cases */
    private static final String UNKNOWN = "unknown";

    private static DocumentBuilder getDocumentBuilder() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception exc) {
            throw new ExceptionInInitializerError(exc);
        }
    }

    /**
     * The XML document.
     */
    private Document doc;
    /**
     * The wrapper for the whole testsuite.
     */
    private Element rootElement;

    /**
     * Where to write the log to.
     */
    private OutputStream out;

    /** No arg constructor. */
    public XMLReport() {
    }

    /** {@inheritDoc}. */
    public void setOutput(OutputStream out) {
        this.out = out;
    }

    
    public void report(TestSuiteResult suite) {
        doc = getDocumentBuilder().newDocument();
        rootElement = doc.createElement(TESTSUITE);
        String n = suite.getTestSuiteName();
        rootElement.setAttribute(ATTR_NAME, n == null ? UNKNOWN : n);

        //add the timestamp
        final String timestamp = DateUtils.format(new Date(),
                DateUtils.ISO8601_DATETIME_PATTERN);
        rootElement.setAttribute(TIMESTAMP, timestamp);

        //and the hostname.
        rootElement.setAttribute(HOSTNAME, getHostname());
        
        rootElement.setAttribute(ATTR_TESTS, "" + suite.getNumOfTestCase());
        rootElement.setAttribute(ATTR_FAILURES, "" + suite.getNumOfFailed());
        rootElement.setAttribute(ATTR_TIME, "" + suite.getDuration());
        for (TestCaseResult result : suite.getResults()) {
            reportTestCase(result);
        }
        writeXML();

    }

    private void reportTestCase(TestCaseResult result) {
        Element testCase = doc.createElement(TESTCASE);
        String name = result.getName();
        testCase.setAttribute(ATTR_NAME,
                                     name == null ? UNKNOWN : name);

        testCase.setAttribute(ATTR_TIME, Float.toString(result.getDuration()));
        //handler failure
        if (!result.isSucceed()) {
            Element failure = doc.createElement(FAILURE);
            failure.setAttribute(ATTR_MESSAGE, result.getErrorMsg());
            testCase.appendChild(failure);
        }
        
        rootElement.appendChild(testCase);
    }

    /**
     * get the local hostname
     * @return the name of the local host, or "localhost" if we cannot work it out
     */
    private String getHostname()  {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

    public void writeXML() throws BuildException {
        if (out != null) {
            Writer wri = null;
            try {
                //wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8"));
                wri = new BufferedWriter(new OutputStreamWriter(out));
                wri.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n");
                Element testSuites = doc.createElement("testsuites");
                testSuites.appendChild(rootElement);
                (new DOMElementWriter()).write(testSuites, wri, 0, "  ");
                wri.flush();
            } catch (IOException exc) {
                throw new BuildException("Unable to write log file", exc);
            } finally {
                if (out != System.out && out != System.err) {
                    FileUtils.close(wri);
                }
            }
        }
    }



} 
